<template>
  <div class="permission-tree-tab">
    <!-- 操作栏 -->
    <el-card class="action-card">
      <div class="action-bar">
        <div class="left-actions">
          <el-button type="primary" @click="handleAddRoot">
            <el-icon><Plus /></el-icon> 添加根权限
          </el-button>
          <el-button type="success" @click="handleExpandAll">
            <el-icon><ArrowDown /></el-icon> 展开全部
          </el-button>
          <el-button @click="handleCollapseAll">
            <el-icon><ArrowUp /></el-icon> 收起全部
          </el-button>
        </div>
        <div class="right-actions">
          <el-button @click="refreshTree">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 权限树 -->
    <el-card class="tree-card">
      <template #header>
        <div class="card-header">
          <span>权限树结构</span>
          <el-tag type="info" size="small">
            共 {{ treeData.length }} 个根节点
          </el-tag>
        </div>
      </template>

      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="treeProps"
        :expand-on-click-node="false"
        :default-expand-all="false"
        node-key="id"
        class="permission-tree"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <div class="menu-node" :class="{ 'dragging': node.isDragging }">
            <div class="node-content">
              <el-icon :size="16" class="node-icon">
                <component :is="getIconComponent(data.icon)" />
              </el-icon>
              <span class="node-label">{{ data.name }}</span>
              <el-tag :type="getTypeTagType(data.type)" size="small" class="type-tag">
                {{ getTypeLabel(data.type) }}
              </el-tag>
              <el-tag v-if="data.method" :type="getMethodTagType(data.method)" size="small" class="method-tag">
                {{ data.method }}
              </el-tag>
            </div>
            <div class="node-actions">
              <el-button type="primary" size="small" @click.stop="handleAddChild(data)">
                添加子权限
              </el-button>
              <el-button type="primary" size="small" @click.stop="handleEdit(data)">
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click.stop="handleDelete(data)"
                :disabled="data.roles && data.roles.length > 0"
              >
                删除
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>

    <!-- 权限详情面板 -->
    <el-card v-if="selectedPermission" class="detail-card">
      <template #header>
        <div class="card-header">
          <span>权限详情</span>
          <el-button type="primary" size="small" @click="handleEdit(selectedPermission)">
            编辑权限
          </el-button>
        </div>
      </template>

      <div class="permission-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="权限名称">
            {{ selectedPermission.name }}
          </el-descriptions-item>
          <el-descriptions-item label="权限代码">
            {{ selectedPermission.code }}
          </el-descriptions-item>
          <el-descriptions-item label="权限类型">
            <el-tag :type="getTypeTagType(selectedPermission.type)">
              {{ getTypeLabel(selectedPermission.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="HTTP方法">
            <el-tag v-if="selectedPermission.method" :type="getMethodTagType(selectedPermission.method)">
              {{ selectedPermission.method }}
            </el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="路径">
            {{ selectedPermission.path || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="组件">
            {{ selectedPermission.component || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="图标">
            <div class="icon-display">
              <el-icon :size="20">
                <component :is="getIconComponent(selectedPermission.icon || '')" />
              </el-icon>
              <span>{{ selectedPermission.icon || '默认图标' }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="排序">
            {{ selectedPermission.order || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="显示状态">
            <el-tag :type="selectedPermission.show ? 'success' : 'info'">
              {{ selectedPermission.show ? '显示' : '隐藏' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="启用状态">
            <el-tag :type="selectedPermission.enable ? 'success' : 'danger'">
              {{ selectedPermission.enable ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="缓存">
            <el-tag :type="selectedPermission.keepAlive ? 'success' : 'info'">
              {{ selectedPermission.keepAlive ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ selectedPermission.description || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>

    <!-- 权限编辑对话框 -->
    <PermissionEditDialog 
      v-model="dialogVisible"
      :permission="currentPermission"
      :is-edit="isEdit"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { 
  Plus,
  ArrowDown,
  ArrowUp,
  Refresh
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import { permissionApi, Permission, PERMISSION_TYPE_OPTIONS } from '../api/permission'
import { getIconComponent } from '../utils/iconUtils'
import PermissionEditDialog from './PermissionEditDialog.vue'

// 树组件引用
const treeRef = ref<InstanceType<typeof ElTree> | null>(null)

// 加载状态
const loading = ref(false)

// 权限树数据
const treeData = ref<Permission[]>([])

// 选中的权限
const selectedPermission = ref<Permission | null>(null)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentPermission = ref<Permission | null>(null)

// 树组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 获取权限树
const fetchPermissionTree = async () => {
  loading.value = true
  try {
    const res = await permissionApi.getPermissionTree()
    
    if (res && res.code === 200) {
      treeData.value = res.data || []
    } else {
      ElMessage.error('获取权限树失败')
    }
  } catch (error) {
    ElMessage.error('获取权限树失败')
  } finally {
    loading.value = false
  }
}

// 刷新树
const refreshTree = () => {
  fetchPermissionTree()
}

// 展开全部
const handleExpandAll = () => {
  if (treeRef.value) {
    const allKeys = getAllNodeKeys(treeData.value)
    ;(treeRef.value as any).setExpandedKeys(allKeys)
  }
}

// 收起全部
const handleCollapseAll = () => {
  if (treeRef.value) {
    ;(treeRef.value as any).setExpandedKeys([])
  }
}

// 获取所有节点键
const getAllNodeKeys = (nodes: Permission[]): number[] => {
  let keys: number[] = []
  nodes.forEach(node => {
    keys.push(node.id)
    if (node.children && node.children.length > 0) {
      keys = keys.concat(getAllNodeKeys(node.children))
    }
  })
  return keys
}

// 添加根权限
const handleAddRoot = () => {
  isEdit.value = false
  currentPermission.value = null
  dialogVisible.value = true
}

// 添加子权限
const handleAddChild = (parent: Permission) => {
  isEdit.value = false
  currentPermission.value = {
    ...parent,
    parentId: parent.id
  } as Permission
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (permission: Permission) => {
  isEdit.value = true
  currentPermission.value = { ...permission }
  dialogVisible.value = true
}

// 删除权限
const handleDelete = (permission: Permission) => {
  if (permission.roles && permission.roles.length > 0) {
    ElMessage.warning('该权限已被角色使用，无法删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除权限 "${permission.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await permissionApi.deletePermission(permission.id)
      
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        fetchPermissionTree()
        selectedPermission.value = null
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 节点点击
const handleNodeClick = (data: Permission) => {
  selectedPermission.value = data
}

// 对话框成功回调
const handleDialogSuccess = () => {
  dialogVisible.value = false
  fetchPermissionTree()
}

// 获取类型标签类型
const getTypeTagType = (type: string): string => {
  const typeMap: Record<string, string> = {
    'MENU': 'primary',
    'BUTTON': 'success',
    'API': 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type: string): string => {
  const option = PERMISSION_TYPE_OPTIONS.find(opt => opt.value === type)
  return option ? option.label : type
}

// 获取方法标签类型
const getMethodTagType = (method: string): string => {
  const methodMap: Record<string, string> = {
    'GET': 'success',
    'POST': 'primary',
    'PATCH': 'warning',
    'DELETE': 'danger'
  }
  return methodMap[method] || 'info'
}

// 加载数据
onMounted(() => {
  fetchPermissionTree()
})
</script>

<style scoped>
.permission-tree-tab {
  padding: 0;
}

.action-card {
  margin-bottom: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 8px;
}

.tree-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-tree {
  min-height: 300px;
}

.menu-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 20px;
  cursor: move;
  transition: all 0.2s ease;
}

.menu-node:hover {
  background-color: var(--el-color-primary-light-9);
  border-radius: 4px;
}

.menu-node.dragging {
  opacity: 0.6;
  transform: scale(0.95);
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-icon {
  color: var(--el-color-primary);
}

.node-label {
  font-weight: 500;
}

.type-tag,
.method-tag {
  margin-left: 4px;
}

.node-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.menu-node:hover .node-actions {
  opacity: 1;
}

.detail-card {
  margin-bottom: 20px;
}

.permission-detail {
  padding: 0;
}

.icon-display {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 树节点内容样式 */
:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
  display: flex;
  align-items: center;
}

/* 展开图标样式 */
:deep(.el-tree-node__expand-icon) {
  margin-right: 8px;
}

/* 重置所有可能影响缩进的样式 */
:deep(.el-tree-node) {
  margin-left: 0 !important;
  padding-left: 0 !important;
}

:deep(.el-tree-node__content-wrapper) {
  margin-left: 0 !important;
  padding-left: 0 !important;
}

/* 使用Element Plus默认的缩进机制 */
:deep(.el-tree-node__children) {
  margin-left: 0 !important;
  padding-left: 0 !important;
}

/* 确保树组件使用默认缩进 */
:deep(.el-tree) {
  --el-tree-node-indent: 18px;
}

/* 修复拖拽时的样式 */
:deep(.el-tree-node.is-drop-inner) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-tree-node.is-drop-inner .el-tree-node__content) {
  background-color: var(--el-color-primary-light-9);
}

/* 拖拽时的占位线样式 */
:deep(.el-tree-node__placeholder) {
  background-color: var(--el-color-primary);
  height: 2px;
  margin: 2px 0;
  border-radius: 1px;
}
</style>
